/**
 * @Author:卿雨欣
 * @Date:2020/7/3
 * @Description:这是产品列表
 */
import React,{Component} from "react";
import {Menu, ActivityIndicator, NavBar, Icon, SearchBar, WhiteSpace, ListView, Tag,Toast} from 'antd-mobile';
import axios from "axios";
import {Link} from "react-router-dom";

// 声明全局变量
var data_list=[] //全部的产品数组
var scroll_list=false; //出现menu菜单的时候，产品列表不能进行滚动
const data = [ // 筛选菜单
    {
        value: '1',
        label: '产品类型',
        children: [
            {
                label: '全部',
                value: '1',
                disabled: false,
            },
            {
                label: '基金型',
                value: '2',
            }, {
                label: '股票型',
                value: '3',
            }, {
                label: '混合型',
                value: '4',
            }],
    }, {
        value: '2',
        label: '产品规模',
        children: [
            {
                label: '≤2亿',
                value: '1',
            }, {
                label: '2~10亿',
                value: '2',
            }],
    },

];

// 将获取的数据中属性为数字的转换为文字
function numberName(newList){
    for(let i=0;i<newList.length;i++) {
        //规范组合产品的收益率
        var ratio = newList[i].totalIncomeRadio;
        newList[i].totalIncomeRadio = Number(ratio*100).toFixed(2)+"%";
        //修改组合产品类型
        switch (newList[i].comBaseCate) {
            case 1:
                newList[i].comBaseCate = "股票型";
                break;
            case 2:
                newList[i].comBaseCate = "基金型";
                break;
            case 3:
                newList[i].comBaseCate = "混合型";
                break;
        }
        //修改组合产品风险等级
        switch (newList[i].comBaseRiskLevel) {
            case 1:
                newList[i].comBaseRiskLevel ="谨慎型";
                break;
            case 2:
                newList[i].comBaseRiskLevel ="稳健型";
                break;
            case 3:
                newList[i].comBaseRiskLevel ="平衡型";
                break;
            case 4:
                newList[i].comBaseRiskLevel ="进取型";
                break;
            default:
                newList[i].comBaseRiskLevel ="激进型";
                break;
        }
        //修改组合产品的状态
        switch (newList[i].isUsed) {
            case 0:
                newList[i].isUsed ="已下架";
                break;
            case 1:
                newList[i].isUsed="预售";
                break;
            case 2:
                newList[i].isUsed ="正在运行";
                break;
        }
    }
    return newList;
};

export default class Product extends Component{
    constructor(...args) {
        super(...args);
        //ListView的dataSource初始化
        const dataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });
        this.state = {
            initData: '',
            show: false,
            //listView
            dataSource,
            isLoading: true,
            data_list:[],
            value:"" ,//搜索栏文字
            pageSize:0,
        };
        this.handleCancel.bind(this)
        this.genData.bind(this)
    }
    //menu选择筛选菜单，回调函数；value，选择的菜单数组的序号数组。例如["1","1"]
    onChange = (value) => {
        let label = '';
        data.forEach((dataItem) => {
            if (dataItem.value === value[0]) {
                label = dataItem.label;
                if (dataItem.children && value[1]) {
                    dataItem.children.forEach((cItem) => {
                        if (cItem.value === value[1]) {
                            label += ` ${cItem.label}`;
                        }
                    });
                }
            }
        });
    }
    // menu点击筛选图标的函数动作
    handleClick = (e) => {
        e.preventDefault();
        scroll_list = true;
        this.setState({
            show: !this.state.show,
        });
        if (!this.state.initData) {
            setTimeout(() => {
                this.setState({
                    initData: data,
                });
            }, 500);
        }
    }
    //点击灰度遮盖层的回调函数，设置灰度遮盖层可见性为false
    onMaskClick = () => {
        scroll_list = false;
        this.setState({
            show: false,
        });
    }
    // 提交搜索 values:搜索框中的字符串
    searchSubmit = (values) =>{
        //初始化产品列表的dataSource
        const newDataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });
        var newDataList = []; //符合搜索条件的新数组
        for(let i=0;i<this.state.data_list.length;i++){
            //查询组合代码
            if(this.state.data_list[i].comBaseCode.indexOf(values) !== -1){
                newDataList.push(this.state.data_list[i])
            }
            //查询组合名称
            if(this.state.data_list[i].comBaseName.indexOf(values) !== -1){
                newDataList.push(this.state.data_list[i])
            }
        }
        //未查询到符合条件的产品，进行提示
        if(newDataList.length === 0){
            Toast.info("未查找到符合条件的产品")
        }else{
            //查询到，更新产品列表listView的dataSource以及列表的item数组data_list，列表展示的数据条数pageSize
            this.setState({
                data_list:newDataList,
                pageSize:newDataList.length,
                dataSource:newDataSource,
            })
            //重新加载产品列表数据dataSource
            this.componentDidMount();
        }
    }
    //搜索栏 取消操作
    handleCancel =(value)=>{
        //初始化产品列表的dataSource
        const newDataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });
        //取消查询清空搜索框的值，恢复产品列表，更新产品列表listView的dataSource以及列表的item数组data_list，列表展示的数据条数pageSize
        this.setState({
            data_list:data_list,
            value:"",
            pageSize:data_list.length,
            dataSource:newDataSource,
        })
        //重新加载产品列表数据dataSource
        this.componentDidMount();
    }
    //搜索栏 值改变的回调函数
    onChangeSearch= (value) => {
        this.setState({ value });
    };
    //初始化产品列表的行列
    genData(pIndex = 0) {
        var NUM_ROWS = this.state.pageSize;
        const dataBlob = {};
        for (let i = 0; i < NUM_ROWS; i++) {
            const ii = (pIndex * NUM_ROWS) + i;
            dataBlob[`${ii}`] = `row - ${ii}`;
        }
        return dataBlob;
    }
    //获取页面数据
    componentWillMount() {
        axios({
            method:"GET",
            url:"http://39.101.141.248:9527/combinations/getCombinationsList",
            params:{}

        }).then(res=>{
            if(res.data.code == 200){
                data_list=numberName(res.data.combinationList) //将对象内的数字属性转化为文字
                this.setState({
                    data_list:data_list,
                    pageSize:data_list.length,
                })
            }
        }).catch(error=>{
            console.log(error);
        });
    }
    //请求初始化数据
    componentDidMount() {
        setTimeout(() => {
            this.rData = this.genData();
            this.setState({
                dataSource: this.state.dataSource.cloneWithRows(this.rData),
                isLoading: false,
            });
        }, 600);
    }
    // 分页请求
    onEndReached = (event) => {
        if (this.state.isLoading) {
            return;
        }
    }

    render() {
        const { initData, show } = this.state;
        const menuEl = ( //筛选菜单
            <Menu
                className="foo-menu"
                data={initData}
                /*   value={['1','2']}*/
                onChange={this.onChange}
                height={document.documentElement.clientHeight * 0.6}
            />
        );
        const loadingEl = ( //面板
            <div style={{ width: '100%', height: document.documentElement.clientHeight * 0.6, display: 'flex', justifyContent: 'center' }}>
                <ActivityIndicator size="large" />
            </div>
        );

        //ListView间隔
        const separator = (sectionID, rowID) => (
            <div
                key={`${sectionID}-${rowID}`}
                style={{
                    backgroundColor: '#F5F5F9',
                    height: 8,
                    borderTop: '1px solid #ECECED',
                    borderBottom: '1px solid #ECECED',
                }}
            />
        );
        let index = this.state.data_list.length - 1;
        //列表的item
        const row = (rowData, sectionID, rowID) => {
            if (index < 0) {
                index = this.state.data_list.length - 1;
            }
            const obj = this.state.data_list[index--];
            return (
                <Link to={{pathname:"/positionList",state:{comBaseId:obj.comBaseId,comBaseName: obj.comBaseName,
                        conBaseStartMoney: obj.conBaseStartMoney,comBaseCate: obj.comBaseCate,
                        comBaseRiskLevel:obj.comBaseRiskLevel}}}>{/*onClick={()=>{this.props.func(this.props.comBaseId)}}*/}
                    <div key={rowID} style={{ padding: '0 15px' }}  >
                        <div
                            style={{
                                lineHeight: '50px',
                                color: '#888',
                                fontSize: 18,
                                borderBottom: '1px solid #F6F6F6',
                            }}
                        >
                            {obj.comBaseName}
                            <Tag style={{color:"#f8a83f",float:"right",marginTop:13}}>{obj.comBaseCate}</Tag>
                        </div>
                        <div style={{ display: '-webkit-box,flex', padding: '10px 0' }}>
                            {/* <img style={{ height: '64px', marginRight: '15px' }} src={obj.img} alt="" />*/}
                            <div style={{ lineHeight: 1 }}>
                                <div className="productList" >
                                    <ul className="productList-ul" >
                                        <li className="font3">
                                            {obj.comBaseRiskLevel}
                                            <p className="gray-text">风险等级</p>
                                        </li>
                                        <li className="font1">
                                            {obj.totalIncomeRadio}
                                            <p className="gray-text">成立以来收益率</p>
                                        </li>
                                        <li className="font2">
                                            {obj.isUsed}
                                            <p className="gray-text">组合状态</p>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </Link>
            );
        };
        return (
            <div >
                <div className={show ? 'menu-active' : ''}>
                    <div style={{position:"fixed",zIndex:500,top:0,left:0,width:"100%"}}>
                        <NavBar
                            mode="light"
                            // icon={<Icon type="left" style={{color:" #f8a83f"}} />}
                            /*onLeftClick={() => this.props.history.push("/")}*/
                            rightContent={
                                <img src={require("../../access/images/filterProductList.png")}
                                     className="am-icon am-icon-md"
                                     onClick={this.handleClick}/>
                            }
                        >
                            <SearchBar value={this.state.value}
                                       style={{width:"230%",zIndex:99,marginLeft:-100,marginRight:-100}}
                                       onCancel={value => this.handleCancel(value)}
                                       onSubmit={value =>this.searchSubmit(value)}
                                       onChange={this.onChangeSearch}
                                       placeholder="组合代码/名称/经理/公司等关键词"  />
                        </NavBar>
                    </div>
                    {show ? initData ? menuEl : loadingEl : null}
                    {show ? <div className="menu-mask" onClick={this.onMaskClick} /> : null}
                </div>
                <WhiteSpace size="lg"/>
                <WhiteSpace size="lg"/>
                <div style={{height:25}}></div>
                <div className={scroll_list ? 'list-scroll' : ''} >
                    <ListView
                        ref={el => this.lv = el}
                        dataSource={this.state.dataSource}
                        renderFooter={() => (<div style={{ padding: 0, textAlign: 'center' }}>
                            {this.state.isLoading ? '加载中' : '已全部加载'}
                        </div>)}
                        renderRow={row}
                        renderSeparator={separator}
                        className="am-list"
                        pageSize={this.state.pageSize}
                        scrollEventThrottle={5}
                        useBodyScroll
                        scrollRenderAheadDistance={500}
                        onEndReached={this.onEndReached}
                        onEndReachedThreshold={10}
                    />
                </div>
            </div>
        );
    }
}
